package com.cwj.film.service.impl;


import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.cwj.common.Beans.film.requestBeans;
import com.cwj.common.domain.FilmFolder;
import com.cwj.common.domain.film;
import com.cwj.common.domain.user;
import com.cwj.common.utils.utils;
import com.cwj.common.vo.film.aboutSo;
import com.cwj.film.Listener.Beans;
import com.cwj.film.dao.FilmFolderDao;
import com.cwj.film.service.inter.about;
import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.core.type.TypeReference;
import com.fasterxml.jackson.databind.ObjectMapper;
import org.springframework.beans.BeanUtils;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.*;
import java.net.URLEncoder;
import java.nio.charset.StandardCharsets;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;
import java.util.zip.ZipOutputStream;

@Service
public class  aboutImpl implements about {
    @Resource
    private HttpServletRequest request;
   @Resource
    private HttpServletResponse response;
    @Resource
    private com.cwj.film.dao.filmDao filmDao;
    @Resource
    private ObjectMapper objectMapper;
    @Resource
    private Beans beans;
    @Resource
    private com.cwj.film.dao.userDao userDao;
    @Resource
    private FilmFolderDao filmFolderDao;
    @Override
    public film GetFilmByTitleType(film film) throws JsonProcessingException {

        Map<String,String> map = objectMapper.readValue(objectMapper.writeValueAsString(film), new TypeReference<>() {});
        film = filmDao.selectOne(new QueryWrapper<film>().allEq(map));
        return film;
    }
    @Override
    public film GetFilmFileByTitleType(film film) throws InterruptedException {

        File[] pictPath = new File(beans.get_1140x1032path()).listFiles();

        List<File> collect = Arrays.stream(pictPath != null ? pictPath : new File[0]).filter(file -> file.getName().substring(0, file.getName().lastIndexOf(".")).equals(film.getTitle())).collect(Collectors.toList());

        film.set_1140x1032pict( collect.size()>0 ? collect.get(0).getAbsolutePath().substring(beans.getServerPath().length()) : null);

        String videoPaths = beans.getServerPath()+"film\\" + film.getType() + "\\" + film.getTitle();
        File[] videos = new File(videoPaths).listFiles();
        assert videos != null;
        int length = videos.length;
        film.setEpisodes(length);
        film.setVideoPath(new ArrayList<>(length));

        for(int i=0;i<videos.length;i++){
            File file = videos[i];
            film.getVideoPath().add(file.getAbsolutePath().substring(beans.getServerPath().length()));
        }


        return film;
    }

    @Override
    public void downFilm(String video) throws IOException {

        List<Closeable>  closeableList = ((requestBeans)request.getAttribute("requestBeans")).getCloseableList();

        File file = new File(beans.getServerPath()+"\\"+video);
        response.setHeader("Content-disposition" , "attachment;filename=" + URLEncoder.encode(file.getName(), StandardCharsets.UTF_8));

        BufferedInputStream bis=new BufferedInputStream(new FileInputStream(file));
        closeableList.add(bis);

        ServletOutputStream sos = response.getOutputStream();
        closeableList.add(sos);

        byte[] by=new byte[1024*1024];
        int len;
        while ((len=bis.read(by))!=-1){ sos.write(by,0,len); }
    }

    @Override
    public void downAll(String title, String type) throws IOException {
        List<Closeable>  closeableList = ((requestBeans)request.getAttribute("requestBeans")).getCloseableList();

        response.setHeader("Content-disposition" , "attachment;filename=" + URLEncoder.encode(title+".zip", StandardCharsets.UTF_8));

        String videos = beans.getServerPath() + "film\\" + type +"\\"+ title;
        File[] files = new File(videos).listFiles();

        ZipOutputStream zos=new ZipOutputStream(response.getOutputStream());
        closeableList.add(zos);
        assert files != null;
        for (File file : files) {
            utils.doZip(file,zos,closeableList);
        }

    }

    @Override
    public Boolean UpdateFolder(Map<String, String> userMap, aboutSo aboutSo) throws JsonProcessingException {
         user user = userDao.selectOne(new QueryWrapper<user>().allEq(userMap));
        if(user!=null){
            Integer uid = user.getUid();
            film film = new film();
            BeanUtils.copyProperties(aboutSo,film);
            com.cwj.common.domain.film selectOne = filmDao.selectOne(new QueryWrapper<film>().allEq(objectMapper.readValue(objectMapper.writeValueAsString(film), new TypeReference<Map<String,String>>() {})));
            if(selectOne!=null){
                Integer fid = selectOne.getFid();
                FilmFolder filmFolder = new FilmFolder();
                filmFolder.setFid(fid);
                filmFolder.setUid(uid);
                if("add".equals(aboutSo.getStatus())){
                    filmFolderDao.insert(filmFolder);
                }else if("delete".equals(aboutSo.getStatus())){
                        filmFolderDao.deleteByMap(objectMapper.readValue(objectMapper.writeValueAsString(filmFolder),new TypeReference<>(){}));
                }
            }
            return true;
        }
        return false;
    }

    @Override
    public Boolean selectFilmFolder(Map<String, String> userMap, aboutSo aboutSo) throws JsonProcessingException {
        user user = userDao.selectOne(new QueryWrapper<user>().allEq(userMap));
        if(user!=null){
            film film = new film();
            BeanUtils.copyProperties(aboutSo,film);
            com.cwj.common.domain.film selectOne = filmDao.selectOne(new QueryWrapper<film>().allEq(objectMapper.readValue(objectMapper.writeValueAsString(film),new TypeReference<Map<String,String>>(){})));
          if(selectOne!=null){
              FilmFolder filmFolder = new FilmFolder();
              filmFolder.setUid(user.getUid());
              filmFolder.setFid(selectOne.getFid());
              Integer integer= filmFolderDao.selectCount(new QueryWrapper<FilmFolder>().allEq(objectMapper.readValue(objectMapper.writeValueAsString(filmFolder),new TypeReference<Map<String,String>>(){})));
              return integer != null && integer > 0;
          }
        }
        return false;
    }

}
